import uiautomator2 as u2
import time
import xml.etree.ElementTree as ET

# 连接设备
d = u2.connect()  # 默认连接已通过adb连接的设备

# 打开抖音
d.app_start("com.ss.android.ugc.aweme")  # 抖音的包名

# 等待应用启动
time.sleep(5)

# 尝试找到点赞按钮并点击
def like_video():
    try:
        like_button = d(resourceId="com.ss.android.ugc.aweme:id/root_layout")
        if like_button.exists:
            like_button.click()
            print("点赞成功")
        else:
            print("未找到点赞按钮")
    except Exception as e:
        print(f"点赞失败: {e}")

# 滑动屏幕
def swipe_down():
    # 获取当前页面的控件树
    xml_hierarchy = d.dump_hierarchy()

    # 解析XML
    root = ET.fromstring(xml_hierarchy)
    traverse_tree(root)

    # d.swipe(300, 2000, 300, 100)  # (x1, y1, x2, y2)
    print("滑动到下一个视频")

def traverse_tree(element, indent=0):
    print(' ' * indent + f"{element.tag} - {element.attrib}")
    for child in element:
        traverse_tree(child, indent + 2)

# 主循环
try:
    while True:
        like_video()
        time.sleep(2)  # 等待2秒，防止操作过快
except KeyboardInterrupt:
    print("程序中断")

# 停止应用
# d.app_stop("com.ss.android.ugc.aweme")